<?php

namespace app\admin\controller;

use app\common\controller\AdminController;

//引入外部函数
use app\common\model\hfztcy\LibMember;
use app\common\model\hfztcy\LibStore;
use app\common\model\hfztcy\LibStoresApply;
use common\Common;
use think\Db;
use think\Exception;


/**
 * 门店申请
 * @name StoresApply.php
 * @package hfztcy
 * @message controller
 * @author rxy
 * @version 1.0
 * @copyright CHANGE INC
 * @since 2020-6-5
 */
class StoresApply extends AdminController
{
    protected $model;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new LibStoresApply();
        $this->rightVerify(session('admin'), url("admin/Login/login"));
        parent::__construct();
    }

    /**
     * 列表页
     */
    function storeApplyList()
    {
        $this->getSetMenu($this);
        $this->log(__CLASS__, __FUNCTION__, "列表页", 1, 'view');
        return $this->fetch('StoresApply/storeApplyList/storeApplyList');
    }

    /**
     * 删除
     */
    function deleteStoreApply()
    {
        $id = input("id");
        $messageRes = $this->model->findStoreApply(['id' => $id]);
        if ($messageRes['errorCode'] == 0) {
            $result = $this->model->deleteStoreApply($id);
            echo json_encode($result);
            die();
        }
        echo json_encode(Common::errorArray(1, '不存在', false));
        die();
    }

    /**
     * 分页查询
     */
    function pagingStoreApply()
    {
        $args = $this->getArgsList($this, ['username']);
        $page = $this->getPageInfo();
        $where = [];
        if (!empty($args['username'])) $where[] = "`memberUsername` like '%" . $args['username'] . "%'";
        $result = $this->model->pagingStoreApply($page, implode(' AND ', $where));
        echo json_encode($result);
    }

    /**
     * Info: 审核用户
     * Date: 2022/6/20 11:24
     */
    public function auditStatus()
    {
        $id = input("id");
        $status = input("state");

        $result = $this->model->findStoreApply(['id' => $id]);
        if ($result['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1, '不存在', ''));
            die();
        }
        if ($result['data']['audit_state'] > 0) {
            echo json_encode(Common::errorArray(1, '已审核', ''));
            die();
        }

        Db::startTrans();
        try {
            if ($status == 1) {
                $reason = '审核成功';
            } else {
                $reason = input("reason");
            }
            $data['audit_state'] = $status;
            $data['audit_msg'] = $reason;
            $data['audit_time'] = Common::getTime();

            $this->model->updateStoreApply(['id' => $id], $data);
            $code = 0;
            $msg = "更新成功";
            $flag = true;
            Db::commit();
        } catch (Exception $exception) {
            $code = 1;
            $msg = "更新失败" . $exception->getMessage();
            $flag = false;
            Db::rollback();
        }
        echo json_encode(Common::errorArray($code, $msg, $flag));
        die();
    }

    /**
     * Info: 绑定门店
     * Date: 2022/11/14 10:52
     */
    function assignStore ()
    {
        $user_id = input("user_id",0);
        $store_id = input("store_id",0);

        Db::startTrans();
        try {
            // 更新店铺信息
            $model = new LibStore();
            $model->updateStore(['id' => $store_id] , ['user_id' => $user_id,'bind_time' => Common::getTime()]);

            // 更新用户身份
            $sql = <<< SQL
SELECT identity FROM `base_user` WHERE `id` = {$user_id}
SQL;
            $userRes = Db::query($sql);
            $userRes = $userRes[0];
            $identity = [];
            if ($userRes) {
                $identity = explode(',',$userRes['identity']);
            }
            array_push($identity,4);
            //排除游客，普通会员，增加门店身份
            $identity = array_map(function ($val) use ($identity) {
                if ($val <= 1) {
                    unset($identity[$val]);
                } else {
                    return $val;
                }
            },$identity);
            $identity = array_filter($identity);
            $identity = array_unique($identity);
            if ($identity) {
                $identityStr = implode(',', $identity);
                $sql = <<< SQL
UPDATE base_user 
SET identity='{$identityStr}' 
WHERE `id` = '{$user_id}'
SQL;
                Db::execute($sql);

                $sql = <<< SQL
UPDATE hfztcy_user 
SET state='{$identityStr}' 
WHERE `user_id` = '{$user_id}'
SQL;
                Db::execute($sql);
            }
            Db::commit();
            echo json_encode(Common::errorArray(0, '绑定成功', true));
            die();
        } catch (Exception $exception) {
            Db::rollback();
            echo json_encode(Common::errorArray(1, '绑定失败-'.$exception->getMessage(), true));
            die();
        }
    }
}

?>